<template>
  <n-form :model="form" :rules="rules" ref="formRef" size="large">
    <n-form-item path="username">
      <n-input placeholder="输入用户名" v-model:value="form.username"/>
    </n-form-item>
    <n-form-item path="password">
      <n-input type="password" placeholder="输入密码" v-model:value="form.password"
               @keydown.enter.prevent="handleLogin"/>
    </n-form-item>
  </n-form>
  <n-button type="primary"
            circle
            :loading="loading"
            size="large"
            block @click="handleLogin">
    登录
  </n-button>
</template>

<script setup lang="ts">

import {ref} from "vue";
import { encrypt} from "@/utils";
import {useDebounceFn} from '@vueuse/core'
import {useUserStore} from "@/store/user";
import api from "@/api";


const loading = ref(false)
const userStore = useUserStore()
const form = ref<ILoginForm>({
  username: '',
  password: '',
})

const formRef = ref()
const rules = ref({
  username: [{
    required: true,
    message: '请输入用户名',
    trigger: ['input']
  }],
  password: [{
    required: true,
    message: '请输入密码',
    trigger: ['input']
  }],
})

const handleLogin = useDebounceFn(() => {
  formRef.value.validate((error: any) => {
    if (!error) {
      loading.value = true
      api.user.login({
        username: form.value.username,
        password: encrypt(form.value.password)
      }).then((res: any) => {
        if (res.data.code === 0) {
          userStore.successLogin(res.data.data.userInfo, res.data.data.token, res.data.data.refreshToken)
          window.$message.success(res.data.msg)
        }
      }).finally(() => {
        loading.value = false
      })
    }
  })
}, 200)
</script>

<style scoped>

</style>
